package org.kev.transit;

import java.util.*;

import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import org.kev.transit.data.Direction;
import org.kev.transit.util.TransitConst;
import org.kev.transit.util.TransitUtil;
import org.kev.transit.worker.DataWorker;

/**
 * Direction screen.  Depending on the tranist system.  This will be the last stop on the line.
 * And the first Stop on the line.  This is show based on a Web service(JSON) call that is then cached in
 * the local DB.  Some day it will also expire cached data in the DB.
 * @author kevin
 *
 */
public class DirectionActivity extends DataActivity{
	public static final int BACK_ID = FIRST_MENU+1;
	public static final int NEXT_ID = FIRST_MENU + 2;
	public static final int SETTINGS_ID = FIRST_MENU + 3;
	public static final String TAG = "Transit";
	private static final DataWorker mWorker=new DataWorker(); 
	// private EditText mEditor;

	private ListView mDirectionView = null;
	private ArrayAdapter <Direction> arrayAdaptor=null;
    // Need handler for call backs to the UI thread
    final Handler mHandler = new Handler();

    
	public DirectionActivity() {

	}

/**
 *  Called when fist started
 *  @param icicle
 */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		try {
			
			// Inflate our UI from its XML layout description.
			getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
	//		Log.d(TAG,"INFLAGE XML!!!");
			setContentView(R.layout.direction);
		        
			mDirectionView = (ListView) findViewById(R.name.directionList);

			//setRouteTypeData();
			mDirectionView.setOnItemSelectedListener(mDirectionListener );
			mDirectionView.setOnItemClickListener(mItemListener);
	

		} catch (Exception e) {
			Log.e(TransitConst.TAG,"UKNOWN Error in "+this,e);
			AlertDialog.show(this,"StackTrace",R.drawable.icon, e.getMessage(), "Ok", false);
		}
	}
	
	
	/**
	 * Called when the activity is about to start interacting with the user.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TransitConst.TAG,".onResume restore Prefs !");
		getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
		mWorker.init(this,mHandler,mUpdateResults);
		Thread t = new Thread(mWorker);
		t.setDaemon(true);
		t.start();
	}
/**
 * 
 * I am being paused save all prefs
 */
	@Override
	protected void onPause() {
		super.onPause();
		
		Log.d(TransitConst.TAG,"onPAUSE Save Prefs!");
		Log.d(TransitConst.TAG,TransitConf.toXML() );
		TransitUtil.savePref(this,TransitConst.DIRECTION_PREF, TransitConf.currentDirection);
	}
	
    @Override
    protected void onFreeze(Bundle outState) {
    	super.onFreeze(outState);
    	TransitUtil.savePref(this,TransitConst.ROUTE_PREF,TransitConf.currentRoute );
        // Remember state
      //  outState.putBundle("transit-view", mLunarView.saveState());
    }
	/**


	/**
	 * Called when your activity's options menu needs to be created.
	 * @param menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// We are going to create two menus. Note that we assign them
		// unique integer IDs, labels from our string resources, and
		// given them shortcuts.

		return true;
	}

	/**
	 * Called right before your activity's option menu is displayed.
	 *  @param menu
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		// Before showing the menu, we need to decide whether the clear
		// item is enabled depending on whether there is text to clear.
		// menu.setItemShown(CLEAR_ID, mEditor.getText().length() > 0);

		return true;
	}

	/**
	 * Called when a menu item is selected.
	 *  @param item
	 *  
	 */  
	@Override
	public boolean onOptionsItemSelected(Menu.Item item) {
		switch (item.getId()) {
		case BACK_ID:
			finish();
			return true;
		case NEXT_ID:
			nextScreen();
			// startActivity(new Intent(Intent..MAIN_ACTION) );
			// mEditor.setText("");
			// mEditor.setText("");
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
	/**
	 * Jump to next Screen (StopActivity)
	 */
	public void nextScreen(){

		this.startActivity(TransitConst.STOP_INTENT);
	}

	/**
	 * set Data on this List view
	 */
	public void setData(){
		 Cursor cursor=null;
		try{
			//	ArrayAdapter<CharSequence> directionAdaptor =ArrayAdapter.createFromResource(  this, R.array.direction, android.R.layout.simple_spinner_item);			
			//	mDirectionSpin.setAdapter(directionAdaptor);
			
			String rType = TransitConf.currentRouteTypeId;
			String route = TransitConf.currentRouteId;
			if( rType ==null ||route ==null){ //if any are null do not set any data
				return;
			}
			Uri curi  = Direction.CONTENT_URI;
			Intent i = new Intent();
			i.setData(curi);
			setIntent(i);
	        ArrayList <Direction> list = Direction.getData(this, rType, route);
	        	        arrayAdaptor = new  ArrayAdapter <Direction> (this,android.R.layout.simple_list_item_1,list);
	        
		}catch(Exception e){
			Log.e(TAG,"setDirction()",e);
		}finally{
			if (cursor!=null)
				cursor.close();
		}
	}


	/**
	 *   save selected item in a TransitConf object
	 */
	private void directionSelected(){
		
		Log.d(TransitConst.TAG,"direction selected");

		if( mDirectionView.getSelectedItem()!=null){
			Direction temp = (Direction) mDirectionView.getSelectedItem();
			TransitConf.currentDirection=temp.title;
			TransitConf.currentDirectionId=temp.id;
			Log.d(TransitConst.TAG,"direction selected");
		}

	}
	/**
	 * set the currently select direction item based on pref if it exist
	 * @param directionSpin
	 */
	private void setCurrentDirection(ListView directionList) {
	       SharedPreferences settings = getSharedPreferences(TransitConst.PREFS_NAME, 0);
		   String current = settings.getString(TransitConst.DIRECTION_PREF,"none");
		   Log.d(TAG,"current direct pref="+current);
		   ListAdapter adaptor= directionList.getAdapter();
		   int count =directionList.getCount();
		   for (int i=0;i<count;i++){
			   String s =adaptor.getItem(i).toString();
			   Log.d(TransitConst.TAG,"current pref="+current);
			   if (s.equals(current) && s!=null){
				   Log.d(TransitConst.TAG,"found slection"+s);
				   directionList.setSelection(i);
				   return;
			   }
		   }
	}
	//****************INNER CLASSES***********************************
	   // Create runnable for posting

    /**
     *  Create runnable for posting UI updates
     */
   Runnable mUpdateResults = new Runnable() {

    	public void run() {
    		Log.d(TAG,"set mUpdateResults.run()="+arrayAdaptor);
    		mDirectionView.setAdapter(arrayAdaptor);
    		setCurrentDirection(mDirectionView);
           	getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,Window.PROGRESS_VISIBILITY_OFF);
        }
    };
	/**
	 * A call-back for click on a selected item
	 */
    OnItemClickListener mItemListener = new OnItemClickListener() {

		public void onItemClick(  AdapterView   arg0 , View arg1, int arg2, long arg3) {
			nextScreen();
			
		}
	};
	/**
	 * A call-back for when the user presses the Next button.
	 */
/*	OnClickListener mNextListener = new OnClickListener() {
		public void onClick(View v) {
			nextScreen();
		}
	};
	*/
	/**
	 * A call-back for when the user presses the back button.
	 */
/*	OnClickListener mBackListener = new OnClickListener() {
		public void onClick(View v) {
			finish();
		}
	};*/
	/**
	 * A call-back for when select a direction.
	 */
	OnItemSelectedListener mDirectionListener = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView parent, View v, int position, long id){
			
			directionSelected();
		}
		public void onNothingSelected(AdapterView parent){
			Log.d(TAG,"NOTHING SELECTED"+parent);
		}
	};

}